/*
 * @Author: lduoduo
 * @Date: 2021-04-13 14:38:40
 * @Last Modified by: lduoduo
 * @Last Modified time: 2021-04-23 18:34:51
 * 流程编辑页面右边的属性面板
 */

import React, { useEffect, useState, useRef } from 'react';
import { debounce } from 'lodash';

import EventBus from '~/utils/events';
import Form from '~/components/Form';

import { getInputs } from './consts';

import { formatPropertyToRemote, formatPropertyToLocal } from './helper';

const onPostChange = debounce((...e) => EventBus.emit('post-data', ...e), 500);

// 节点信息
const PropertiesNode = (props) => {
  const { modeler, className, isRoot, onTabSwitch } = props;

  const refValueString = useRef('');
  const refValue = useRef({});
  const refShape = useRef({});
  const [value, setValue] = useState({});
  const [visible, setVisible] = useState(false);

  // 由于两个tab共用一个组件，所以这里提一个方法出来判断是否是当前tab，非当前tab不处理数据
  const isCurrTab = (v) => {
    const t = (isRoot && v.$type === 'bpmn:Process') || (!isRoot && v.$type !== 'bpmn:Process');
    setVisible(t);

    // 自动切换tab
    !isRoot && onTabSwitch(t ? 0 : 1);

    return t;
  };

  const onReceiveChange = (e, shape) => {
    if (!isCurrTab(e)) return;

    const d = formatPropertyToLocal(e);

    if (refValueString.current === JSON.stringify(d)) return;
    refValueString.current = JSON.stringify(d);

    refValue.current = e;
    refShape.current = shape;
    setValue(d);
  };

  const onChange = (e, d) => {
    // setValue(e);
    refValueString.current = JSON.stringify(e);

    console.log('onChange', e, d);

    const [value, shape] = formatPropertyToRemote(
      d,
      refValue.current,
      modeler.current,
      refShape.current
    );

    onPostChange(value, shape || refShape.current);
  };

  useEffect(() => {
    EventBus.on('element-data', onReceiveChange);
    isRoot && setTimeout(() => EventBus.emit('sync-data', 'root'), 1000);
  }, []);

  useEffect(() => {
    EventBus.on('ready', (e) => {
      // console.log('modeler', modeler, modeler.current, e);
    });
  }, [modeler]);

  const { name, $type } = value;

  if (!visible) return null;

  const inputs = getInputs($type);

  return (
    <Form
      className={`comp-form ${className}`}
      value={value}
      inputs={inputs}
      onChange={onChange}
    />
  );
};

export default PropertiesNode;
